package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.Favorite_z;
import com.scuec.groupfive.mapper.Favorite_zMapper;
import com.scuec.groupfive.service.Favorite_zService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class Favorite_zServiceImpl implements Favorite_zService {

    @Resource
    private Favorite_zMapper favoriteZMapper;

    @Override
    public List<Favorite_z> getFavoriteList(Long userId) {
        return favoriteZMapper.selectByUserId(userId);
    }

    @Override
    @Transactional
    public boolean addFavorite(Long userId, Long questionId) {
        try {
            // 检查是否已存在记录
            if (favoriteZMapper.exists(userId, questionId) > 0) {
                // 如果存在，则更新状态为1
                return favoriteZMapper.updateStatus(userId, questionId, 1) > 0;
            }

            // 检查是否存在但状态为0的记录
            if (favoriteZMapper.checkExists(userId, questionId) > 0) {
                // 如果存在但状态为0，则更新状态为1
                return favoriteZMapper.updateStatus(userId, questionId, 1) > 0;
            }

            // 不存在则插入新记录
            Favorite_z favorite = new Favorite_z();
            favorite.setUserId(userId);
            favorite.setQuestionId(questionId);
            favorite.setStatus(1);
            favorite.setCreatedAt(LocalDateTime.now());
            favorite.setUpdatedAt(LocalDateTime.now());

            return favoriteZMapper.insert(favorite) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    @Override
    @Transactional
    public boolean removeFavorite(Long userId, Long questionId) {
        System.out.println("Removing favorite: userId=" + userId + ", questionId=" + questionId);
        return favoriteZMapper.delete(userId, questionId) > 0;
    }

    @Override
    public boolean isFavorite(Long userId, Long questionId) {
        return favoriteZMapper.exists(userId, questionId) > 0;
    }
}